package app.caihan.scframe.base

import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.multidex.MultiDexApplication
import app.caihan.scframe.common.loadinghelper.*
import app.caihan.scframe.util.isNightMode
import app.caihan.scframe.util.setNightMode
import com.blankj.utilcode.util.ProcessUtils.isMainProcess
import com.blankj.utilcode.util.Utils

/**
 * BaseApp
 *
 * @author Seven-C
 * @date 2020/7/27
 */
abstract class BaseApp : MultiDexApplication(), ViewModelStoreOwner {

    private val mAppViewModelStore: ViewModelStore by lazy { ViewModelStore() }
    private val mFactory by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(this)
    }

    private val mViewModelProvider by lazy { ViewModelProvider(this, mFactory) }

    override fun onCreate() {
        super.onCreate()
        // 主进程初始化
        if (isMainProcess()) {
            initApp()
        }
    }

    private fun initApp() {
        Utils.init(this)
        LoadingHelper.setDefaultAdapterPool {
            register(
                ViewType.LOADING,
                LoadingAdapter()
            )
            register(
                ViewType.ERROR,
                ErrorAdapter()
            )
            register(
                ViewType.EMPTY,
                EmptyAdapter()
            )
        }
        setDayNightMode()
    }


    /**
     * 设置夜间模式
     */
    private fun setDayNightMode() {
        setNightMode(!isNightMode(this))
    }

    override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore
    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return mViewModelProvider
    }

}